package com.vertxExample.starter;

import io.vertx.core.AbstractVerticle;
import io.vertx.core.Promise;
import io.vertx.core.json.JsonObject;
import io.vertx.ext.web.Router;

/**
 * 获取路由参数
 */
public class UrlParamsVerticle extends AbstractVerticle {
	// create object router
	Router router;


	@Override
	public void start(Promise<Void> startPromise) throws Exception {
		// set router
		Router router = Router.router(vertx);
		// start web application and bind router
		// router绑定的路径，才会解析
		router.route("/").handler(req -> {
			req.response()
				.putHeader("content-type", "application/json")
				.end(new JsonObject().put("hello", "Hello from Vert.x!").toString());
		});
		// 经典模式 http://localhost:8888/test?page
		router.route("/test").handler(req -> {
			var page = req.request().getParam("page"); // vert.x get url parameters

			req.response()
				.putHeader("content-type", "application/json")
				.end(
					new JsonObject().put("hello", "Hello from Vert.x!")
						.put("page", page)
					.toString());
		});
		// 路由模式 http://localhost:8888/test?page
		router.route("/test/:page").handler(req -> {
			var page = req.request().getParam("page"); // vert.x get url parameters
			System.out.println(page);
			req.response()
				.putHeader("content-type", "application/json")
				.end(
					new JsonObject().put("hello", "Hello from Vert.x!")
					.put("page", page)
					.toString()
				);
		});

		// config url
		vertx.createHttpServer().requestHandler(router).listen(8888, http -> {
			if (http.succeeded()) {
				startPromise.complete();
				System.out.println("HTTP server started on port 8888");
			} else {
				startPromise.fail(http.cause());
			}
		});
	}
}
